package com.zz.hhbl.ui

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zz.framework.core.adapter.KotlinAdapter
import com.zz.framework.core.base.BaseFragment
import com.zz.framework.core.event.RecordSosInfoEvent
import com.zz.framework.core.ext.dp
import com.zz.framework.core.ext.fromJson
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.toJson
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.utils.DataStoreUtils
import com.zz.framework.core.utils.EncryptUtils
import com.zz.framework.core.utils.MediaPlayerUtils
import com.zz.framework.core.utils.ZInterval
import com.zz.framework.widget.CustomPopWindow
import com.zz.framework.widget.RecordButton
import com.zz.hhbl.R
import com.zz.hhbl.databinding.FragmentTestTranslateBinding
import com.zz.hhbl.databinding.PopListBinding
import com.zz.hhbl.databinding.PopListItemBinding
import com.zz.hhbl.entity.KeyValueEntity
import com.zz.hhbl.entity.TranslateEntity
import com.zz.hhbl.ui.translate.TestTranslateAdapter
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import kotlin.getValue

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/31 10:22.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class TestTranslateFragment : BaseFragment(R.layout.fragment_test_translate) {
    val SHARED_PREFERENCES_TRANSLATE_LIST = "SHARED_PREFERENCES_TRANSLATE_LIST"
    private val viewModel: CommonViewModel by viewModels()
    private val binding: FragmentTestTranslateBinding? by viewBinding()
    var adapter: TestTranslateAdapter = TestTranslateAdapter()
    var mSourceLanguage = KeyValueEntity("0", "中文")
    var mTargetLanguage = KeyValueEntity("1", "英文")
    val languageList = listOf(
        KeyValueEntity("0", "中文"),
        KeyValueEntity("1", "英文"),
        KeyValueEntity("2", "韩文"),
        KeyValueEntity("3", "日文"),
        KeyValueEntity("4", "法语"),
    )

    override fun initView() {
        super.initView()
        binding?.btnAudio?.setOnFinishedRecordListener(object : RecordButton.OnFinishedRecordListener {
            override fun onFinishedRecord(audioPath: String, time: Int) {
//                val audioPath = binding!!.btnAudio.localFolderPath+"/aaa.mp3"
//                viewModel.audioCreate(mSourceLanguage.key, mTargetLanguage.key, audioPath)
//                addOrUpdate(TranslateEntity(status = 1, text = audioPath, url = audioPath, taskId = "task_id_${System.currentTimeMillis()}", isUserVoice = true))
            }
        })
        binding?.apply {
            recyclerView.layoutManager = LinearLayoutManager(requireActivity())
            recyclerView.adapter = adapter
            tvSourceLanguage.onClick {
                showPopListView(tvSourceLanguage, languageList)
            }
            ivExchange.onClick {
                val temp = mSourceLanguage;
                mSourceLanguage = mTargetLanguage
                mTargetLanguage = temp
                tvSourceLanguage.setText(mSourceLanguage.value)
                tvTargetLanguage.setText(mTargetLanguage.value)
            }
            tvTargetLanguage.onClick {
                showPopListView(tvTargetLanguage, languageList)
            }
        }
        adapter.submitList(getAllList())
        adapter.setItemClickListener { item ->
            if (item.isUserVoice) {
                item.url?.let {
                    if (MediaPlayerUtils.getInstance().isPlaying()){
                        MediaPlayerUtils.getInstance().stop()
                    }else {
                        MediaPlayerUtils.getInstance().playAudioByUrl(it) {}
                    }
                }
            } else {
                item.url?.let {
                    if (MediaPlayerUtils.getInstance().isPlaying()){
                        MediaPlayerUtils.getInstance().stop()
                    }else {
                        MediaPlayerUtils.getInstance().playAudioByUrl(it) {}
                    }
                }
            }
        }
        viewModel.audioCreateLiveData.observe(viewLifecycleOwner) {
            addOrUpdate(it)
        }
        viewModel.audioGetStatusLiveData.observe(viewLifecycleOwner) {
            addOrUpdate(it)
        }
        sosInterval.start()
    }


    val sosInterval = object : ZInterval(10 * 1000) {
        override fun onInterval() {
            getAllList().filter { it.status == 0 && it.isUserVoice.not() }.forEach {
                viewModel.audioGetStatus(it)
            }
        }
    }

    fun addOrUpdate(item: TranslateEntity) {
        val list = getAllList().map {
            if (it.taskId == item.taskId) {
                it.status = item.status
                it.text = item.text
                it.url = item.url
            }
            it
        }.toMutableList()
        list.find { it.taskId == item.taskId } ?: let {
            list.add(item)
        }
        DataStoreUtils.putSyncData(SHARED_PREFERENCES_TRANSLATE_LIST, list.toJson())
        adapter.addOrUpdateData(item)
    }

    fun getAllList(): MutableList<TranslateEntity> {
        return DataStoreUtils.getSyncData(SHARED_PREFERENCES_TRANSLATE_LIST, "[]").fromJson<MutableList<TranslateEntity>>()
    }

    override fun onDestroyView() {
        clearData()
        MediaPlayerUtils.getInstance().stop()
        super.onDestroyView()
    }

    fun clearData() {
        DataStoreUtils.putSyncData(SHARED_PREFERENCES_TRANSLATE_LIST, "[]")
    }


    var mListPopWindow: CustomPopWindow? = null
    private fun showPopListView(anchor: View, list: List<KeyValueEntity>) {
        val listBinding = PopListBinding.inflate(LayoutInflater.from(requireActivity()))
        handleListView(listBinding, list) {
            when (anchor) {
                binding?.tvSourceLanguage -> {
                    mSourceLanguage = it
                    binding?.tvSourceLanguage?.setText(it.value)
                }

                binding?.tvTargetLanguage -> {
                    mTargetLanguage = it
                    binding?.tvTargetLanguage?.setText(it.value)
                }
            }
            mListPopWindow?.dissmiss()
            mListPopWindow = null
        }
        mListPopWindow = CustomPopWindow.PopupWindowBuilder(requireActivity())
            .setView(listBinding.root)
            .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
            .setBgDarkAlpha(0.7f) // 控制亮度
            .size(120.dp(), ViewGroup.LayoutParams.WRAP_CONTENT) //显示大小
            .create()
            .showAsDropDown(anchor, 0,  5)
    }

    private fun handleListView(listBinding: PopListBinding, list: List<KeyValueEntity>, action: (KeyValueEntity) -> Unit) {
        val recyclerView = listBinding.recyclerView
        val manager = LinearLayoutManager(requireActivity())
        manager.setOrientation(LinearLayoutManager.VERTICAL)
        recyclerView.setLayoutManager(manager)
        val adapter = KotlinAdapter.Builder<KeyValueEntity, PopListItemBinding>(PopListItemBinding::class.java)
            .addBindView { holder, item ->
                holder?.binding?.tvContent?.text = item?.value
            }
            .onItemClick { holder, item ->
                item?.let {
                    action.invoke(item)
                }
            }
            .setNewData(list)
            .create()
        recyclerView.setAdapter(adapter)
    }


}